<?php

include_once($ROOT . "model/dao/User.php");
include_once($ROOT . "model/dao/UserRoleMap.php");

class UserUtil {

	function getAccess()
	{
		include ($ROOT . "access.inc.php");
		return $__ACCESS;
	}

	function hasPermission($role, $page)
	{
		$__ACCESS = self::getAccess();

		if (is_array($role))
		{
			foreach ($role as $r)
			{
				if (in_array($page, $__ACCESS[$r]))
				{
					return true;
				}
			}
		}
		else
		{
			if (in_array($page, $__ACCESS[$role]))
			{
				return true;
			}
		}
		return false;
	}

	function getAvailableRoles()
	{
		$access = self::getAccess();

		$roles = array();
		foreach ($access as $role => $pagesArray)
		{
			array_push($roles, $role);
		}
		return $roles;
	}

	function getCurrentUser()
	{
		global $_SESSION;

		if (!isset($_SESSION)) session_start();

		$id = $_SESSION['user_id'];
		if ($id == null || $id == "")
			return false;

		$userDao = new UserDAO();

		return $userDao->get($id);
	}

	function getRoles($user_id)
	{
		$userRoleMapDao = new UserRoleMapDAO();

		$userRoleMaps = $userRoleMapDao->findWhere("user_id = $user_id");

		$roles = array();
		foreach ($userRoleMaps as $userRoleMap)
		{
			array_push($roles, $userRoleMap->role);
		}

		return $roles;
	}

	function authenticate ($username, $password)
	{
		global $_SESSION;
		if ($password == null || strlen($password) == 0)
			return false;

		//$username = safeEscapeStr($username);
		//$password = safeEscapeStr($password);

		$userDao = new UserDAO();

		$users = $userDao->findWhere("username = '$username' and password = MD5('$password')");

		if (count($users) == 1)
		{
			// Add it to session
			$user = $users[0];
			session_start();
			$_SESSION['user_id'] = $user->id;

			return true;
		}

		return false;
	}

	function logout ()
	{
		session_destroy();
	}


}

?>
